package com.lee.chapter01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Test_Volatile2 {
    static volatile int num = 0;
    static AtomicInteger integer = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                // num++操作不是原子操作，读取/运算/赋值
                num++;
                // 保证了原子性
                integer.getAndIncrement();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                num++;
                integer.getAndIncrement();
            }
        });
        thread1.start();
        thread2.start();

        TimeUnit.SECONDS.sleep(3);
        System.out.println("num:" + num);
        System.out.println("integer:"+integer.get());
    }
}
